$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_tssxsp_m")
    const dgrid3 = $NG.getCmpApi("p_form_tssxsp_d3")
    const dgrid3_bar = $NG.getCmpApi("toolbar_p_form_tssxsp_d3")
    const dgrid2 = $NG.getCmpApi("p_form_tssxsp_d2")
    const dgrid2_bar = $NG.getCmpApi("toolbar_p_form_tssxsp_d2")
    const getHeadValue = (str) => mstform.getItem(str).getValue()

    const config = {
        d1data: [],
        d2data: []
    }

    useClick(()=>{
        getFileId()
    },"u_mb")

    useUpdateRows(() => {
        const rows = dgrid3.getRows()
        let total_amt = 0
        rows.forEach(el => {
            el.u_fyxj1 = (Number(el.u_cl1) || 0) + (Number(el.u_jx1) || 0) + (Number(el.u_qtfy) || 0) + (Number(el.u_sj1) || 0)
            el.u_dydcbhtje = (Number(el.u_gcl) || 0) * (Number(el.u_dj) || 0)
            el.u_nfb2 = (Number(el.u_nfb1) || 0) * (Number(el.u_gcl) || 0)
            el.u_qtfy2 = (Number(el.u_qtfy) || 0) * (Number(el.u_gcl) || 0)
            el.u_lr2 = (Number(el.u_hj) || 0) - (Number(el.u_nfb2) || 0) - (Number(el.u_fyxj2) || 0)
            el.u_lr1 = (Number(el.u_lr2) || 0) / (Number(el.u_gcl) || 0)
            el.u_cl2 = (Number(el.u_cl1) || 0) * (Number(el.u_gcl) || 0)
            el.u_jx2 = (Number(el.u_jx1) || 0) * (Number(el.u_gcl) || 0)
            el.u_sj2 = (Number(el.u_sj1) || 0) * (Number(el.u_gcl) || 0)
            el.u_fyxj2 = (Number(el.u_cl2) || 0) + (Number(el.u_jx2) || 0) + (Number(el.u_qtfy2) || 0) + (Number(el.u_sj2) || 0)
            el.u_hj = (Number(el.u_gcl) || 0) * (Number(el.u_dj) || 0)
            total_amt += (Number(el.u_nfb2) || 0)
        })
        mstform.getItem("u_gjfbjk").setValue(total_amt)
        dgrid3.refreshView()
    }, "p_form_tssxsp_d3")
 
    // useUpdateRows(() => {
    //     const row = dgrid2.getRows()
    //     row.forEach(item => {
    //         if (item.u_log == '1') {
    //             const el = config.d1data.filter(it => {
    //                 if (it.u_sourceid == item.u_sourceid) {
    //                     return it
    //                 }
    //             })
    //             if (el.length == 1) {
    //                 const element = el[0]
    //                 for (let key in element) {
    //                     item[key] = element[key]
    //                 }
    //                 dgrid2.refreshView()
    //             }
    //             return
    //         }
    //     })
    // }, "p_form_tssxsp_d2")

    useUpdateRow(({args})=>{
        const row = args[0]
        if (row.u_log == '1') {
            $NG.message("当前行是导入数据不可修改！")  
            const el = config.d1data.filter(it => {
                    if (it.u_sourceid == row.u_sourceid) {
                        return it
                    }
                })
                if (el.length == 1) {
                    const element = el[0]
                    for (let key in element) {
                        row[key] = element[key]
                    }
                    dgrid2.refreshView()
                }
                return
        }
    },"p_form_tssxsp_d2")

    dgrid2_bar.insert({
        id: "d1_myadd",
        text: "明细选择",
        iconCls: "icon-New"
    });

    dgrid3_bar.insert({
        id: "d2_myadd",
        text: "明细选择",
        iconCls: "icon-New"
    });

    useClick(() => {
        helpD1()
    }, "d1_myadd")

    useClick(() => {
        helpD2()
    }, "d2_myadd")

    useValuesChange(async () => {
        dgrid2.clearRows()
        dgrid3.clearRows()
        const phid = getHeadValue("u_fbxmchsbh")
        if (!phid) return
        const res = await $NG.execServer("SELECT", { sql: `select m.phid_pc, project.bill_name from p_form_fbch_m m left join project_table project on project.phid = m.phid_pc where m.phid = '${phid}'` })
        if (res.count == 0) return
        const datas = JSON.parse(res.data)[0].extendObjects
        mstform.getItem("u_gcxmmc").setValue({
            label: datas.bill_name,
            value: datas.phid_pc
        })
    }, "p_form_tssxsp_m.u_fbxmchsbh")

    function helpD1() {
        const phid = getHeadValue("u_fbxmchsbh")
        if (!phid) {
            $NG.alert("请先选择分包策划！")
            return
        }
        //自定义打开帮助
        $NG.external.openNGHelp({
            type: "NGMultipleHelp",//NGSingleHelp
            helpId: "fbch_d2",
            valueField: "phid",
            labelField: "u_fbxmmc",
            clientSqlFilter:
                `a.pphid = '${phid}'`
        }).then((data) => {
            // console.log(`data`,data,data.reduce);
            const arr = data.reduce((value, item) => {
                console.log(`item`, item);
                const el = item.origin
                const lock = dgrid2.getRows().some(it => it.u_sourceid == el.phid)
                if (lock) {
                    return value
                }
                value.push({
                    rel_key1: el.rel_key1,
                    u_fbxmmc: el.u_fbxmmc,
                    u_sourceid: el.phid,
                    u_log: "1"
                })
                return value
            }, [])
            config.d1data = [...config.d1data, ...arr]
            dgrid2.addRows(arr)
            //data:拿到帮助选中的数据
        })
    }

    function helpD2() {
        const row = dgrid2.getSelectedData()
        const phid = getHeadValue("u_fbxmchsbh")
        if (row.length == 0) {
            $NG.alert("请先中一条父明细！")
            return
        }
        if (!phid) return
        //自定义打开帮助
        $NG.external.openNGHelp({
            type: "NGMultipleHelp",//NGSingleHelp
            helpId: "fbch_d3",
            valueField: "phid",
            labelField: "s_tree_name",
            clientSqlFilter:
                `a.pphid = '${phid}' and a.rel_key1 = '${row[0].rel_key1}'`
        }).then((data) => {
            // console.log(`data`,data,data.reduce);
            let arr = data.reduce((value, item) => {
                console.log(`item`, item);
                const el = item.origin
                const lock = dgrid3.getRows().some(it => it.u_sourceid == el.phid)
                if (lock) {
                    return value
                }
                value.push({
                    rel_key1: el.rel_key1,
                    s_tree_no: el.s_tree_no,
                    s_tree_name: el.s_tree_name,
                    u_sourceid: el.phid,
                    u_dw: el.u_dw,
                    u_gcl: el.u_gcl,
                    u_dj: el.u_dj,
                    u_hj: el.u_hj,
                    u_nfb1: el.u_nfbje,
                    u_lr1: el.u_lr,
                    u_cl1: el.u_cl,
                    u_jx1: el.u_jx,
                    u_qtfy: el.u_qtfy,
                    u_sj1: el.u_sj,
                    u_fyxj1: el.u_fyxj,
                    u_cl2: el.u_clje,
                    u_qtfy2: el.u_qtfyje,
                    u_sj2: el.u_sjje,
                    u_fyxj2: el.u_fyxjje,
                    u_dydcbhtje: el.u_dydcbhtje,
                    u_lr2: el.u_lrje,
                    u_nfb2: el.u_nfb,
                    u_bz: el.u_bz,
                    s_tree_pid: el.s_tree_pid,
                    s_tree_id: el.s_tree_id,
                    u_dw_EXName: el.msname,
                    u_log: "1"
                })
                return value
            }, [])
            console.log(`arr1`, arr);
            arr = arrayToTree(arr, "s_tree_id", "s_tree_pid")
            console.log(`arr2`, arr);
            dgrid3.addRows(arr)
            //data:拿到帮助选中的数据
        })
    }

    // 转属性结构
    function arrayToTree(items, idField = "id", parentField = "parentId", childrenField = "children") {
        const map = {};
        const roots = [];

        // 先建立 id → item 的映射
        items.forEach(item => {
            map[item[idField]] = { ...item, [childrenField]: [] };
        });

        // 组装树
        items.forEach(item => {
            const parentId = item[parentField];
            if (parentId == null || parentId.length < 2 || parentField == '0') {
                // 根节点
                roots.push(map[item[idField]]);
            } else if (map[parentId]) {
                // 挂到父节点的 children 上
                map[parentId][childrenField].push(map[item[idField]]);
            }
        });

        return roots;
    }
 // 查询附件，找到附件的数量
    async function getFileId() {
        let asr = null
        await $NG.execServer("getAttachmentByasr", { code: 'eb2394c8-dd08-419d-9d59-8651dbee293e' }, (res) => {
            if (res.count == 0) {
                asr = null
            } else {
                asr = JSON.parse(res.data)[0].extendObjects
            }
        })
        if (!asr) {
            $NG.alert("没有模板可以下载！")
            return
        }
        const origin = location.origin;
        const router = "/JFileSrv/reactAttach/download";
        const param = {
            asrFid: asr.asr_fid,
            asrName: asr.asr_name,
            busTypeCode: "drmb",
            loginId: "6870000000000016",
            orgId: "1",
            asrFilldt: asr.asr_filldt
        };

        const query = new URLSearchParams(param).toString();
        const url = `${origin}${router}?${query}`;

        try {
            // 1. fetch 请求，加上你需要的 header
            const res = await fetch(url, {
                method: "GET",
                headers: {
                    "Authorization": localStorage.getItem("Auth$#$i8$#$6.3sp1$#$lsz"),
                    "dbtoken": "0001", // 🔴 在这里加请求
                }
            });

            if (!res.ok) {
                throw new Error("下载失败: " + res.status);
            }
            // 从响应头解析文件名
            const disposition = res.headers.get("Content-Disposition");
            let filename = asr.asr_name
            if (disposition && disposition.includes("filename=")) {
                const match = disposition.match(/filename="?([^"]+)"?/);
                if (match.length > 1) {
                    filename = decodeURIComponent(match[1]);
                }
            }
            // 转 blob
            const blob = await res.blob();

            // 创建临时链接并下载
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.download = filename; // ✅ 指定文件名
            link.target = "_blank";
            document.body.appendChild(link);
            link.click();
            link.remove();

            setTimeout(() => URL.revokeObjectURL(link.href), 60000);
        } catch (err) {
            console.error(err);
            $NG.alert("下载出错啦！");
        }
        // const button = document.createElement('a');
        // button.style.display = 'none'
        // button.href = url
        // document.body.appendChild(button);
        // button.click()

    }
})